from websocket_server import WebsocketServer
import asyncio
import json
import threading

import websocket
from websocket import create_connection


def new_client(client, server):
    print("当新的客户端连接时会提示:%s" % client['id'])
    cmd = {'cmd': '', 'state': '', 'msg': ''}
    cmd['cmd'] = 'msg'
    cmd['msg'] = 'Hey all, a new client has joined us'
    server.send_message(client, json.dumps(cmd))
    cmd['cmd'] = 'name'
    cmd['msg'] = ''
    server.send_message(client, json.dumps(cmd))


def client_left(client, server):
    print("client %s disconnected" % client['id'])


def message_received(client, server, message):
    try:
        ljmsg = json.loads(message)
        print(ljmsg)
        if ljmsg['cmd'] == "name":
            client['id'] = ljmsg['msg']
        if ljmsg['dest'] == "broadcast":
            server.send_message_to_all(message)
        else:
            # 转发消息给特定人
            server.send_message_to(ljmsg['dest'], message)
    except Exception as identifier:
        pass


# @asyncio.coroutine
# def startwb():
#     server = WebsocketServer(12345, "0.0.0.0")
#     server.set_fn_new_client(new_client)
#     server.set_fn_client_left(client_left)
#     server.set_fn_message_received(message_received)
#     server.run_forever()


# asyncio.get_event_loop().run_until_complete(startwb())
# asyncio.get_event_loop().run_forever()

def startwb():
    def start():
        server = WebsocketServer(12345, "0.0.0.0")
        server.set_fn_new_client(new_client)
        server.set_fn_client_left(client_left)
        server.set_fn_message_received(message_received)
        server.run_forever()
    # t = threading.Thread(target=start)
    # t.start()
    start()


def sendmsg(msg):
    ws = create_connection("ws://127.0.0.1:12345")
    ws.send(msg)
    result = ws.recv()
    ws.close()


# if __name__ == "__main__":
# startwb()
